//
//  uiButtonBox.cpp
//  trail-map-editor
//
//  Created by Tino Giorgio on 12/2/13.
//
//

#include "ui.h"

using namespace tinyxml2;

uiButtonBox::uiButtonBox(int minx, int miny, int maxx, int maxy, char** labels, int one_button) : puButtonBox(minx, miny, maxx, maxy, labels, one_button)
, items(0)
, list(0)
{
    this->items = new ulList();
}

uiButtonBox::~uiButtonBox()
{
    this->clear();
}

void uiButtonBox::load(const tinyxml2::XMLElement* element)
{
	uiData* data = (uiData*)this->getUserData();
	
	if(!data)
		ulSetError(UL_WARNING,"uiButtonBox::load() called before the user data was set. Callbacks won't work!");
	
    this->clear();
    
	if(element)
		parseElement(element->FirstChildElement());
    
    //
    // Loading is done, let's add all the entries
    //
    this->close();
}

void uiButtonBox::parseElement(const tinyxml2::XMLElement* element)
{
	const XMLElement* sibling = element;
	
	while(sibling)
	{
		beginElement(sibling);
		
		const XMLElement* child = sibling->FirstChildElement();
		
		if(child)
			parseElement(child);
		
		endElement(sibling);
		
		sibling = sibling->NextSiblingElement();
	}
}

void uiButtonBox::beginElement(const XMLElement* element)
{
	if(XMLUtil::StringEqual( element->Name(), "buttonboxitem" ))
    {
		const char* legend = element->Attribute("legend");
		
        //
        // NOTE : here we create a duplicate fo the string
        //
		this->items->addEntity(ulStrDup(legend));
    }
}

void uiButtonBox::endElement(const XMLElement* element)
{
    //
    // Nothing to do
    //
}

void uiButtonBox::close()
{
    int n = this->items->getNumEntities();
    
    if(n > 0)
    {
        this->list = new char*[n+1];
        
        for(unsigned int i = 0; i < n; i++)
        {
            //
            // NOTE : here we save the same instance, no copy!
            //
            list[i] = (char*)this->items->getEntity(i);
        }
    }
    
    list[n]=NULL;
    
    this->newList(this->list);
}

void uiButtonBox::clear()
{
    this->newList(NULL);
    
    int n = this->items->getNumEntities();
    
    for(unsigned int i = 0; i < n; i++)
    {
        //
        // NOTE : here we finally get rid of the char* (the legend)
        //
        delete[] list[i];
    }
    
    delete[] list;
    
    //
    // This does not delete the entities! This is why we have just deleted them before!
    //
    this->items->removeAllEntities();
}
